import * as faceapi from "face-api.js";

let withBoxes = true
const checkbox = document.getElementById('checkbox')
checkbox.addEventListener('change',function(e){
    document.getElementById('box').removeChild(document.getElementsByTagName('canvas')[0])
    withBoxes = e.target.checked
    main()
})

main()

async function main(){
    // 加载模型权重文件
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')

    await faceapi.loadFaceLandmarkModel('http://127.0.0.1:8888/weights')

    const input = document.getElementById('image')

    // 根据图片创建一个画布，用户显示人脸方框
    let canvas = faceapi.createCanvasFromMedia(input)
    const container = document.getElementById('box')
    container.prepend(canvas)
    const displaySize = { width:input.width, height:input.height }
    faceapi.matchDimensions(canvas, displaySize)

    //获取图片中的全部人脸特征数据
    const options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.38 })
    const results = await faceapi.detectAllFaces(input, options).withFaceLandmarks()
    faceapi.matchDimensions(canvas, input)

    const resizedResults = faceapi.resizeResults(results, input)

    if (withBoxes) {
        //将检测结果绘制到画布中
        faceapi.draw.drawDetections(canvas, resizedResults)
    }
    //将人脸68个点绘制到画布中
    faceapi.draw.drawFaceLandmarks(canvas, resizedResults)

    closeLoading()
}


